package com.kangfu.api.service.impl;

import com.kangfu.api.service.ILeaveRecordService;
import com.kangfu.common.exception.BusinessException;
import com.kangfu.db.domain.entity.LeaveRecord;
import com.kangfu.db.mapper.LeaveRecordMapper;
import com.kangfu.db.model.request.LeaveRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

@Service
public class LeaveRecordServiceImpl implements ILeaveRecordService {

    @Autowired
    public LeaveRecordMapper leaveRecordMapper;

    @Override
    public int insertLeaveRecord(int userId ,LeaveRequest leaveRequest) {
        //检查请假的时间是否合理
        LocalDate todayDate = LocalDate.now();
        System.out.println(todayDate);
        System.out.println(leaveRequest.getStartDate());
        System.out.println(leaveRequest.getEndDate());
        if (leaveRequest.getStartDate().isAfter(leaveRequest.getEndDate())) {
            throw new BusinessException("开始时间不能大于结束时间");
        }
        if (leaveRequest.getStartDate().isBefore(todayDate)|| leaveRequest.getEndDate().isBefore(todayDate)) {
            throw new BusinessException("开始时间和结束时间不得小于当前时间");
        }
        //检查是否已经有请过假
        LeaveRecord findLeaveRecord = leaveRecordMapper.checkLeaveRecordByDate(userId,leaveRequest.getStartDate(),leaveRequest.getEndDate());
        if (findLeaveRecord != null) {
            throw new BusinessException("您已经请过假了");
        }

        LeaveRecord leaveRecord = new LeaveRecord();
        leaveRecord.setReason(leaveRequest.getReason());
        leaveRecord.setStartDate(leaveRequest.getStartDate());
        leaveRecord.setEndDate(leaveRequest.getEndDate());
        leaveRecord.setUserId(userId);
        leaveRecord.setCreateTime(LocalDateTime.now());
        return leaveRecordMapper.insertLeaveRecord(leaveRecord);
    }

    @Override
    public List<LeaveRecord> selectLeaveRecordList(int userId, int page) {
        int pageSize = 5;
        int offset = (page - 1) * pageSize;
        return leaveRecordMapper.selectLeaveRecordList(userId, offset, pageSize);
    }

}
